<template >
  <div class="setting-content inside-comment">
    <el-scrollbar height="calc(100vh - 170px)">
      <div class="layout">
        <!-- <h2 class="setting-header">
          <strong>留言详情</strong>
        </h2> -->
        <div class="list-back" @click="listBack"><el-icon><DArrowLeft /></el-icon>返回列表</div>
        <div class="form-box">
          <div class="item-row form-name">{{ commentData.name }}</div>
          <div class="item-row" v-if="commentData.description != ''">{{ commentData.description }}</div>
          <Form :fields="commentData.content" ref="formRef" :model-value="{}" label-width="100px" />
          <div class="dialog-footer">
            <div class="left-box">
              <el-switch v-if="commentSetting?.allowAnonymousQuestion" v-model="addFormData.isAnonymity" inactive-text="是否匿名" style="margin-right: 15px;"/>
              <el-switch v-model="addFormData.isPublic" inactive-text="是否公开" />
            </div>
            <div class="right-box">
              <el-button @click="resetForm">重置</el-button>
              <el-button type="primary" @click="saveForm">提交</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { selectfunction } from "@/api/setting"; 
import { selectByIdCommentForm } from "@/api/form"; 
import { insertByFrontCommentMessages } from "@/api/comment"; 
import Form from "../components/Form";
import { ElMessage } from "element-plus";
import { getToken } from '@ruifox-cms/utils'
import { DArrowLeft } from '@element-plus/icons-vue';

const formRef = ref(null);
const route = useRoute(); 
const router = useRouter(); 
const hasToken = ref(!!getToken())

const commentData = ref({}); 
const addFormData = reactive({
  catId: 0,
  content: {
    content: "",
  },
  formId: 0,
  pid: 0,
  isAnonymity: false,
  isPublic: true,
  typeId: ""
})
const loadCommentDetail = async () => {
  //检测表单id是否存在，不存在返回留言表列表
  if (!route.query.id) {
    ElMessage.error("表单不存在,即将返回留言表列表页")
    setTimeout(() => {
      listBack();
    }, 1000);
    return
  }
  const id = route.query.id; 
  const res = await selectByIdCommentForm(id); 
  if(res.code === 20000){
    commentData.value = res.data;
    commentData.value.content = res.data.content.map(element => ({
      ...element, // 使用扩展运算符复制原对象的所有属性
      value: "", // 添加 value 属性并初始化为空字符串
    }));
  }
};

//获取留言设置
const commentSetting = ref()
const getCommentSetting = async () => {
  const res = await selectfunction()
  commentSetting.value = res.data 
}

//返回列表
const listBack = () => {
  router.push({ 
    path: '/comment/user/commentFormList', 
  });
}
//重置表单
const resetForm = () => {
  loadCommentDetail(); 
}

//正则校验
const checkList = ref([
  { name:"电话号码", value: 'phone', regular: "^(?:\\+?86)?\\s?(?:1[3-9]\\d{9}|(?:\\d{3,4}|\\(\\d{3,4}\\))\\s?\\d{7,8}(?:\\s?(-|ext\\.?)\\s?\\d{1,5})?)$" },
  { name:"邮箱", value: 'mailbox', regular: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" },
  { name:"身份证号", value: 'numberId', regular: "^\\d{6}(19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$" },
  { name:"邮政编码", value: 'postalCode', regular: "^[1-9]\\d{5}$" },
])

//提交表单
const isSubmitting = ref(false); //提交标志变量，避免重复提交
const saveForm = async () => {
  if (isSubmitting.value) {
    ElMessage({
      showClose: true,
      message: '正在提交，请稍后...',
      type: 'warning'
    });
    return;
  }
  isSubmitting.value = true;
  if (formRef.value) {
    // 调用子组件暴露的 getFormData 方法
    formRef.value.getFormData();
  } 
  let addFormFlag = true  
  commentData.value.content.forEach(element => {
    //判断必填项是否填写
    if (element.required == "true") {
      if (!element.value.trim()) {
        addFormFlag = false
        ElMessage({
          showClose: true,
          message: `请填写${element.label}` ,
          type: 'warning'
        })
        isSubmitting.value = false;
        return
      }
    }
    // 正则校验 
    if (element.type == 'input' && element.check && element.check != "" && element.value != "") {
      const matchedRule = checkList.value.find(item => item.value === element.check);
      if (matchedRule) {
        const regexString = matchedRule.regular.replace(/^\/|\/$/g, ''); // 去掉首尾的斜杠
        const regex = new RegExp(regexString);
        const isValid = regex.test(element.value); 
        if (!isValid){
          ElMessage({
            showClose: true,
            message: `请填写正确格式的${element.label}` ,
            type: 'warning'
          })
          addFormFlag = false
          return
        }
      } else {
        console.error(`未找到匹配的校验规则: ${element.check}`);
        addFormFlag = false
      }
    }
  });
  if (addFormFlag == false) {
    return
  } else {
    //判断当前是否需要登录
    if (commentSetting.value.needLogin == true) {
      if (!hasToken.value) {
        ElMessage({
          showClose: true,
          message: '请先登录',
          type: 'warning'
        })
        setTimeout(() => {
          router.push('/comment/user/commentFormList')
        }, 1000) // 延迟跳转登录页
      } 
    }
    //如果当前表单有分类 设置typeId 
    commentData.value.content.forEach (element =>{
      if (element.type == "classify") {
        addFormData.typeId = element.value
      }
    }) 
    //其他表单项修改
    addFormData.content.content = commentData.value.content;
    addFormData.formId = commentData.value.id;
    const mailItem = commentData.value.content.find(item => item.check === "mailbox")
    if(mailItem && mailItem.value) {
      addFormData.mailbox = mailItem.value
    }
    console.log("addFormData",addFormData);
    try {
      const res = await insertByFrontCommentMessages(addFormData); 
      if (res.code === 20000) {
        ElMessage.success("提交留言成功");
        loadCommentDetail(); 
        // 调用子组件的 clearFileList 方法清空文件列表
        formRef.value.clearFileList();
      }
    } catch (error) {
      ElMessage.error("留言失败");
    } finally {
      // 无论成功或失败，都需要将提交状态重置为 false
      isSubmitting.value = false;
    }
  }
}

onMounted(async() => {
  await getCommentSetting()
  await loadCommentDetail(); 
});
</script>

<style scoped lang='scss'>
.setting-content{
  margin: 60px auto 0;
  max-height: calc(100vh - 150px);

  /* overflow-y: scroll; */
}
.list-back{
  color: $black_2;
  font-size: 14px;
  line-height: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  i{
    margin-right: 3px;
  }
  &:hover{
    color: $black;
  }
}
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.form-box {
  width: 800px;
  max-width: 100%;
  margin: 10px auto 20px;
  padding: $padding-large;
  box-sizing: border-box;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  .item-row {
    font-size: 16px;
    margin-bottom: 15px;
    color: $mainColor;
    span{
      color: $black;
    }
    &.form-name{
      font-size: 28px;
      font-weight: 600;
      color: $black;
      text-align: center;
      word-break: break-all;
      white-space: pre-wrap;
      margin-bottom: 30px;
      color: $black;
    }
  }
  .dialog-footer{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .right-box{
      display: flex;
      justify-content: end;
    }
  }
}
/*去除富文本下面框*/
::v-deep .tox .tox-statusbar {
  border-top: none;
}
/* 响应式 */
@media (max-width:960px) {
  .form-box{
    padding: 20px;
    border: 1px solid $borderColor;
    .item-row.form-name {
      font-size: 20px;
      margin-bottom: 10px;
    }
  }
}
</style>
